import os
import re
import subprocess
import sys
from time import sleep

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec

def get_application_path():
    if getattr(sys, 'frozen', False):
        application_path = os.path.dirname(sys.executable)
    else:
        application_path = os.path.dirname(__file__)
    print(f'application_path={application_path}')
    return application_path

class WebTool:
    def __init__(self, default_download_path: str):
        self.default_download_path = default_download_path
        app_path = get_application_path()
        app_path = os.path.join(app_path, 'driver')
        self.chrome_version = self._get_chrome_version()
        if self.chrome_version.split('.')[0] == 135:
            self.service = Service(executable_path=os.path.join(app_path, 'chromedriver_135.exe'))
        elif self.chrome_version.split('.')[0] == 136:
            self.service = Service(executable_path=os.path.join(app_path, 'chromedriver_136.exe'))
        else:
            self.service = Service(executable_path=os.path.join(app_path, 'chromedriver_136.exe'))
        
        options_ = webdriver.ChromeOptions()
        options_.add_experimental_option('detach', True)
        if not os.path.exists(default_download_path):
            os.mkdir(default_download_path)
        prefs = {
            "download.default_directory": default_download_path,
            "download.prompt_for_download": False,
            "download.directory_upgrade": True,
            "plugins.always_open_pdf_externally": True
        }
        options_.add_experimental_option("prefs", prefs)
        self.driver = webdriver.Chrome(service=self.service, options=options_)
        self.driver.get("https://www.google.es/")
        self.driver.set_window_size(1000, 1000)   

    def download_file(self, url: str):
        js = "window.open('{}','_blank');"
        self.driver.execute_script(js.format(url))
        self.driver.switch_to.window(self.driver.window_handles[-1])

        try:
            WebDriverWait(self.driver, 10).until(ec.presence_of_element_located((By.XPATH, '//div[contains(@class, "el-dropdown")]')))
            print("页面加载完成")
        except Exception as e:
            print("加载错误")
            self.driver.quit()
        
        download_elem = self.driver.find_element(By.XPATH, '//div[contains(@class, "el-dropdown")]')
        download_item = self.driver.find_element(By.XPATH, '//li[contains(@class, "el-dropdown-menu__item")]')

        actions = ActionChains(self.driver)
        actions.move_to_element(download_elem).pause(0.5).perform()
        download_item.click()

        # 等待下载完成
        match = re.search(r'=(.*)', url)
        num = match.group(1).strip()
        target_file = os.path.join(self.default_download_path, f'smartPref_{num}.zip')
        while True:
            if os.path.exists(target_file):
                print(f"文件下载完成:{target_file}")
                break
            sleep(0.5)

    @staticmethod
    def _get_chrome_version():
        command = ''
        try:
            command = r'wmic datafile where name="C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" get Version /value'
            output = subprocess.check_output(command, shell=True).decode('utf-8')
            version = re.search(r'(\d+\.\d+\.\d+\.\d+)', output).group(1)
            return version
        except Exception as e:
            print(f"获取 Chrome版本失败")
            return None
    